/*
 * @Author: 肖思汗 
 * @Date: 2025-05-17 10:57:41 
 * @Last Modified by: 肖思汗
 * @Last Modified time: 2025-06-14 11:54:13
 */

import utils from "src/utils/utils";
import Api from "./Api";
import { OssToken } from "type";
//接口模版
class UtilsApi extends Api {

    constructor() {
        super();
    }

    // 获取ossToken
    getOssToken() {
        return this._post("/common/oss/getOssUploadToken");
    }

    //上传到oss
    async uploadOss(file: any, dir: string) {
        const { data: ossToken } = await this.getOssToken() as { data: OssToken };

        // 设置文件名
        const fileName = await new Promise<string>(async (resolve1, reject1) => {
            let end = file.name.split('.').pop()?.toLowerCase() || '';
            let id = await utils.getFileMD5(file);

            if (/(jpg|png|peg|webp)/i.test(end)) {
                const img = new Image();

                await new Promise((resolve2, reject2) => {
                    img.onload = () => resolve2(img);
                    img.onerror = reject2;
                    img.src = URL.createObjectURL(file);
                });

                resolve1(`${dir}/${img.width}_${img.height}_${file.size}_${id}.${end}`);
            } else {
                resolve1(`${dir}/${id}.${end}`);
            }
        });

        const formData = new FormData();

        formData.append("success_action_status", "200");
        formData.append("policy", ossToken.policy);
        formData.append("x-oss-signature", ossToken.signature);
        formData.append("x-oss-signature-version", ossToken.version);
        formData.append("x-oss-credential", ossToken.x_oss_credential);
        formData.append("x-oss-date", ossToken.x_oss_date);
        formData.append("x-oss-security-token", ossToken.security_token);
        formData.append('key', fileName);
        formData.append('file', file);

        const response = await fetch(ossToken.host, {
            method: 'POST',
            body: formData
        }).then(res => {
            return res;
        }).catch(err => {
            return err;
        });

        return `/${fileName}`;
    }
}

const utilsApi = new UtilsApi();

export default utilsApi;